/**
 * Created by Administrator on 2017/12/6.
 */
var Code=require("../utils/code");
var iconv=require("iconv-lite");
var utils=require("../utils/utils")
var async=require("async");
exports.bs=function(req,res){
    
    //获取提交的信息并保存到数据库
    if(utils.isNull(req.body)){
        res.send({code:Code.paramsMissingCode,error:"参数错误"});
        return;
    }
    var options={
        platform:req.body.platform==undefined?"":req.body.platform,//平台名称
        commodity_name:req.body.platform==undefined?"":req.body.commodity_name,//商品名称
        price:req.body.price==undefined?"":req.body.price,//商品价格
        is_price:req.body.is_price==undefined?"":req.body.is_price, //是否返款本金 （0 未返款 1 已返款）
        commission:req.body.commission==undefined?0:req.body.commission,//佣金
        is_commission:req.body.is_commission==undefined?"":req.body.is_commission, //是否返款佣金 （0 未返款 1 已返款）
        sign:req.body.sign==undefined?0:req.body.sign,//是否签收 （0 未签收 1 已签收）
        pay:req.body.pay==undefined?0:req.body.pay,//是否代付（0 非代付 1 代付）
        insertTime:req.body.insertTime==undefined?"":req.body.insertTime,//记录时间
        lastTime:req.body.lastTime==undefined?"":req.body.lastTime,//最后操作时间
        commodity_href:req.body.commodity_href==undefined?"":req.body.commodity_href,//商品链接
        business_nike:req.body.business_nike==undefined?"":req.body.business_nike,//商家微信昵称
        business_code:req.body.business_code==undefined?"":req.body.business_code,//微信号码
        is_end:req.body.is_end==undefined?0:req.body.is_end,//是否完结(0 未完结 1 完结)
        shop_name:req.body.shop_name==undefined?"":req.body.shop_name,//店铺名称
        gift:req.body.gift==undefined?"":req.body.gift,//礼品
        imgsrc:req.body.imgsrc==undefined?"":req.body.imgsrc//礼品
    };
    var sql="insert into record_total(platform,commodity_name,price,is_price,commission,is_commission,sign,pay," +
        "insertTime,lastTime,commodity_href,business_nike,business_code,is_end,shop_name,gift,imgsrc) value(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    var params=Object.keys(options).map(function(key){
        return options[key];
    });
    // console.log(params);

    DB.query(sql,params,function(err,result){
        if(err){
            console.log(err.stack);
            res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
            return;
        }
        res.send({code:Code.successCode,error:"",data:"操作成功"});
    })
}

exports.queryBs=function(req,res){
    //查询插入数据库的信息
    //查询总单数
    var totals={};
    var getTotal=function(callBack){
        var sql="select count(*) as total from record_total";
        DB.query(sql,[],function(err,result){
            if(err){
                console.log(err.stack);

                res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
                return;
            }
            totals.listTotal=result[0].total;
            callBack(null);
        })
    }
    //查询垫付金额
    var getPriceTotal=function(cb,cont){
        var sql="SELECT sum(CAST(price as decimal(18,2))) as priceTotal from record_total where pay=0";
        DB.query(sql,[],function(err,result){
            if(err){
                console.log(err.stack);
                res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
                return;
            }
            totals.priceTotal=result[0].priceTotal
            cb(null);
        })
    };
    //查询赚取佣金
    var getCommissionTotal=function(cb,cont){
        var sql="SELECT sum(commission) as commissionTotal from record_total";
        DB.query(sql,[],function(err,result){
            if(err){
                console.log(err.stack);
                res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
                return;
            }
            totals.commissionTotal=result[0].commissionTotal
            cb(null);
        })
    };

    var queryData=function(callBack){
        var pageSize=req.body.pageSize;
        var pageNum=req.body.pageNum;
        var sql="";
        if(!pageSize || !pageNum){
            sql="select * from record_total ORDER BY id DESC";
        }else{
            if(pageNum<=0){
                pageNum=1;//当pageNum小于等于0时，取第一页
            }
            sql="select * from record_total   limit "+(pageNum-1)*pageSize+","+pageSize;
            console.log(sql);
        }
        DB.query(sql,sql,function(err,result){
            if(err){
                console.log(err.stack);
                res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
                return;
            }
            // console.log(result[0].total);
            var params=[];
            for(var i=0;i<result.length;i++){
                var item=result[i];
                params.push({
                    id:item.id,
                    platform:item.platform,
                    commodity_name:item.commodity_name,
                    price:item.price,
                    is_price:item.is_price,
                    commission:item.commission,
                    is_commission:item.is_commission,
                    sign:item.sign,
                    pay:item.pay,
                    insertTime:item.insertTime,
                    lastTime:item.lastTime,
                    commodity_href:item.commodity_href,
                    business_nike:item.business_nike,
                    business_code:item.business_code,
                    is_end:item.is_end,
                    shop_name:item.shop_name,
                    gift:item.gift,
                    imgsrc:item.imgsrc
                });
            }
            // res.send({code:Code.successCode,data:params});
            for(var i=0;i<params.length-1;i++){
                for(var j=i+1;j<params.length;j++){
                    var data_i=new Date(params[i].insertTime).getTime();
                    var data_j=new Date(params[j].insertTime).getTime();
                    if(data_i>data_j){
                        var tmp=params[i];
                        params[i]=params[j];
                        params[j]=tmp;
                    }
                }
            }
            callBack(null,{params,totals})
        })
    }

    async.waterfall([getTotal,getPriceTotal,getCommissionTotal,queryData],function(err,result){
        if(err) throw  err;
        res.send({code:Code.successCode,totals:result.totals,data:result.params});
    });

}

exports.bsUpdate=function(req,res){
    var id=req.body.id;
    if(!id){
        res.send({code:Code.paramsMissingCode,error:"参数错误"});
        return;
    }

    var params=Object.keys(req.body).map(function(key){
        return req.body[key];
    });
    var sql="update record_total set platform=?,commodity_name=?,price=?,is_price=?," +
        "commission=?,is_commission=?,sign=?,pay=?,insertTime=?,lastTime=?,commodity_href=?,business_nike=?," +
        "business_code=?,is_end=?,shop_name=?,gift=?,imgsrc=?  where id=?";

    DB.query(sql,params,function(err,result){
        if(err){
            console.log(err.stack);
            res.send({code:Code.insideErrorCode,error:"服务器内部错误"});
            return;
        }
        res.send({code:Code.successCode,error:"",data:"操作成功"});
    })
}

